import translateService from "./translate-service";
import widgetService from "./widget-service";
import commandService from "./command-service";
import searchService from "./search-service";
import commonService from "./common-service";
import backgroundService from "./background-service";
import logger from "@/components/log";

export const commandTypes = {
    execute: "execute",
    search: "search",
};

class ServiceCenter {
    services = null;
    registedService = null;
    constructor() {
        logger.info("业务中心注册成功");
        this.services = new Map();
        this.registedService = [];
    }

    // 注册业务
    registeService(service) {
        this.registedService.push(service.__getName());
        const _proto = Object.getPrototypeOf(service);
        const keys = Object.getOwnPropertyNames(_proto);
        keys.filter((k) => k != "constructor" && !k.startsWith("_")).forEach(
            (k) => {
                if (!this.services.has(k)) {
                    // 通过key注册，并常驻
                    this.services.set(k, service);
                }
            }
        );
    }

    /**
     * 根据matched的命令和option执行指定函数, 或者执行其他指令
     * @param {*} command 命令, 在event中匹配, asset此处命令正确
     * @param {*} option 命令的option
     * @returns
     */
    execute(command, option) {
        // 命令注册了, 但是处理函数可能未注册, 此处通过has判断不存在后,抛出异常
        try {
            if (!this.services.has(command)) {
                throw new Error(`未注册${command}的处理函数`);
            }
            const executor = this.services.get(command);
            if (option && option.help) {
                return Promise.resolve(executor.showHelp(command));
            } else {
                const res = executor[command](option);
                if (typeof res !== "Promise") {
                    return Promise.resolve(res);
                }
                return res;
            }
        } catch (err) {
            return Promise.reject(err);
        }
    }

    // 调试信息
    report() {
        let reportInfo = "";
        this.registedService.forEach((v) => (reportInfo += `【${v}】`));
        logger.info(`${reportInfo}等业务模块注册成功`);
    }
}

const service = new ServiceCenter();
service.registeService(translateService);
service.registeService(widgetService);
service.registeService(commandService);
service.registeService(searchService);
service.registeService(commonService);
service.registeService(backgroundService);
service.report();
export default service;
